<?php

namespace App\Logic\Auth\Form;

use App\Core\BaseListForm;
use App\Lib\Mongodb\Mongodb;
use EasySwoole\Component\Di;

class SysLogListForm extends BaseListForm{
    
    public $username;
    public $url_path;
    public $method;
    public $optime_begin;
    public $optime_end;

    public function lists(){
        $pagination = $this->getPagination();
        $pagination['total_count'] = 0;
        
        $result = [
            'list'       => [],
            'pagination' => $pagination
        ];
        
        $where = [];
        
        if(strlen($this->username) > 0){
            $where['username'] = ['$regex' => '^'.$this->username.''];
        }
        
        if(strlen($this->url_path) > 0){
            $where['url_path'] = ['$regex' => '^'.$this->url_path.''];
        }
    
        if(strlen($this->method) > 0){
            $where['method'] = ['$regex' => '^'.$this->method.''];
        }
        
        if ( empty($this->optime_begin) || empty($this->optime_end) ){
            return $this->success($result);
        }
        
        $time_begin = date('Ym',strtotime($this->optime_begin));
        $time_end = date('Ym',strtotime($this->optime_end));
        if ( $time_begin != $time_end ){
            return $this->success($result);
        }
        
        //集合
        $collection = 'sys_log-' . $time_begin;
        
        $where['optime'] = [
            '$gte' => strtotime($this->optime_begin),
            '$lte' => strtotime($this->optime_end),
        ];
        
        /** @var Mongodb $mongodb */
        $mongodb = Di::getInstance()->get("MONGODB");
        
        $order = ['optime','desc'];
        
        $list = $mongodb->select($collection, $where,$this->getPagination(),$order);
        
        foreach ($list as $key => $item) {
            $list[$key]['optime'] = date('Y-m-d H:i:s',$item['optime']);
            $list[$key]['params'] = json_decode($item['params'],true);
        }
        
        $pagination = $this->getPagination();
        $pagination['total_count'] = $mongodb->count($collection, $where);
        
        $result = [
            'list'       => $list,
            'pagination' => $pagination
        ];
        
        return $this->success($result);
    }
    
}